import { IEvent } from '../type/IEvent';
import { BNode } from '../type/BNode';
import { Easing } from '../utils/Easing';
import { clamp } from 'cc';
import { Linear } from '../utils/SpeedDistanceTime';

export class TweenNode extends BNode implements IEvent {
    iTime = 0;
    isPause = false;
    blackBoard: any;

    constructor(
        public duration: number,
        public update: (ratio: number, dt: number, blackBoard?: any) => void,
        public easing: (n: number) => number = Easing.linear
    ) {
        super();
    }

    onStart(blackboard?: any): void {
        this.iTime = 0;
        this.blackBoard = blackboard;
    }

    onUpdate(dt: number): void {
        if (this.isPause) {
            return;
        }
        this.iTime += dt;
        this.iTime = clamp(this.iTime, 0, this.duration);

        const v = Linear(0, 1, this.iTime, this.duration, this.easing);
        this.update(v, dt, this.blackBoard);

        if (this.iTime >= this.duration) {
            this.task.done();
        }
    }

    onCancel(): void {
        this.iTime = 0;
    }

    onReset(): void {
        this.iTime = 0;
    }

    onEvent(event: string, data?: any) {
        switch (event) {
            case 'pause':
                this.isPause = true;
                break;
            case 'resume':
                this.isPause = false;
                break;
        }
    }
}
